<template>
    <div class="admin-page">
        <div class="page-header">
            <div style="display: flex;justify-content: space-between">
                <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <div style="display: flex; align-items: center;" class="search-item">
                    <span class="search-label">用户名:</span>
                    <el-input v-model="form.search" placeholder="用户名" size="small" style="width: 160px;"></el-input>
                </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">身份:</span>
                        <el-select v-model="form.source" size="small" style="width: 110px;" placeholder="全部" clearable>
                            <el-option label="全部" value=""></el-option>
                            <el-option label="普通用户" value="1"></el-option>
                            <el-option label="特殊用户" value="2"></el-option>
                        </el-select>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">等级:</span>
                        <el-select v-model="form.is_up" size="small" style="width: 130px;" placeholder="全部" clearable>
                            <el-option label="全部" value=""></el-option>
                            <el-option label="萌新" value="0"></el-option>
                            <el-option label="初级服务商" value="1"></el-option>
                            <el-option label="中级服务商" value="2"></el-option>
                            <el-option label="高级服务商" value="3"></el-option>
                            <el-option label="区级服务商" value="4"></el-option>
                            <el-option label="城市服务商" value="5"></el-option>
                            <el-option label="大区服务商" value="6"></el-option>
                            <el-option label="全球服务商" value="7"></el-option>
                        </el-select>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">日期:</span>
                        <el-date-picker
                            size="small"
                            v-model="form.start_time"
                            type="date"
                            style="width: 130px;"
                            placeholder="开始日期">
                        </el-date-picker>
                        <span style="margin: 0 5px;">至</span>
                        <el-date-picker
                            size="small"
                            v-model="form.end_time"
                            type="date"
                            style="width: 130px;"
                            placeholder="结束日期">
                        </el-date-picker>
                    </div>
                </div>
                <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <el-button type="primary" size="small" @click="toSearch">搜索</el-button>
                    <el-button type="success" size="small" style="margin-left: 10px;" @click="reset">重置</el-button>
                </div>
            </div>

            <el-table :data="adminList" height="560" border style="width: 100%;overflow-y: auto"
                      :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                <el-table-column prop="id" label="ID" width="80" align="center"/>
                <el-table-column prop="username" label="用户名" width="100" align="center"/>
                <el-table-column prop="nickname" label="用户昵称" width="100" align="center"/>
                <el-table-column prop="surplus_grain" label="余粮" width="100" align="center"/>
                <el-table-column prop="pid" label="推荐人" width="120" align="center"/>
                <el-table-column prop="money" label="业绩" width="100" align="center"/>
                <el-table-column prop="up_init_money" label="购买金额" width="100" align="center"/>
                <el-table-column prop="g_pid" label="挂载人" width="120" align="center"/>
                <el-table-column prop="s_g_pid" label="实际挂载人" width="120" align="center"/>
                <el-table-column prop="self_re_code" label="用户邀请码" width="100" align="center"/>
                <el-table-column prop="source" label="用户身份" width="80" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.source === 1 ? '普通用户' : '特殊用户' }}
                    </template>
                </el-table-column>
                <el-table-column prop="is_up" label="等级" width="100"/>
                <el-table-column prop="create_time" label="创建时间" width="150"/>
                <el-table-column label="操作" width="280">
                    <template slot-scope="scope">
                        <el-button type="success" size="small" @click="handleStateChange(scope.row)"
                                   :style="{ backgroundColor: scope.row.state === 0? 'red' : '#67c23a' }">
                            {{ scope.row.state === 0 ? '禁用' : '启用' }}
                        </el-button>
                        <el-button type="success" size="small" @click="toShowDialog(scope.row)">
                            直推树
                        </el-button>
                        <el-button type="success" size="small" @click="toShowDialog1(scope.row)">
                            挂点树
                        </el-button>

                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="15"
                layout="total, prev, pager, next, jumper"
                :total="total"
            />
        </div>
    </div>
</template>

<script>

export default {
    data() {
        return {
            adminList: [],
            currentPage: 1,
            pageSize: 15,
            total: 0,
            form: {
                search: "",
                source: "",
                is_up: "",
                state: "",
                start_time: "",
                end_time: ""
            },
            showDialog: false,
            showDialog1: false,
            centerDialogVisible: false,
            centerDialogVisible1: false,
            userServerList: {
                serverOne: "xxxxxx",
                moneyOne: "1000",
                serverTwo: "xxxxxx",
                moneyTwo: "1000",
                serverThree: "xxxxxx",
                moneyThree: "1000",
            },
            userId: null,
            username: "",
            searchParams:{}
        };
    },
    mounted() {
        this.fetchAdminList();
    },
    methods: {

        handleStateChange(row) {
            const newState = row.state === 1 ? 0 : 1;
            this.$http.post('/admin/User/del', {
                title: row.title,
                clas_id: row.clas_id,
                type: row.type,
                description: row.description,
                thumb: row.thumb,
                content: row.content,
                sort: row.sort,
                pur_price: row.pur_price,
                price: row.price,
                num: row.num,
                admin_id: row.admin_id,
                id: row.id,
                state: newState
            }).then(result => {
                if (result.code === 200) {
                    this.$message.success('状态更新成功');
                    this.fetchAdminList();
                } else {
                    this.$message.error(result.msg || '状态更新失败');
                }
            });
        },
        fetchAdminList(params = {}) {
            const mergedParams = {
                ...params,  // 先展开传入的参数
                page: params.page || this.currentPage,  // 优先使用传入的页码
                limit: 15  // 固定每页显示数量
            };

            // 显示加载状态
            this.$message.info({
                message: '正在加载数据...',
                duration: 0,
                showClose: true,
                iconClass: 'el-icon-loading'
            });
            this.$http.get('/admin/User/lists', {params: mergedParams}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.adminList = newListData;
                    this.total = result.data.total || newListData.length;
                } else {
                    this.$message.error(result.msg);
                }
            }).catch(error => {
                console.error('获取列表失败:', error);
                this.$message.error('获取数据失败，请重试');
            }).finally(() => {
                // 关闭加载提示
                this.$message.closeAll();
            });
        },
        handleSizeChange(val) {
            this.pageSize = 15; // 确保一直是15
            this.fetchAdminList();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.fetchAdminList(this.searchParams);
        },
        toSearch() {
            const formatDate = (date) => {
                if (!date) return '';
                const d = new Date(date);
                const year = d.getFullYear();
                const month = String(d.getMonth() + 1).padStart(2, '0');
                const day = String(d.getDate()).padStart(2, '0');
                const hours = String(d.getHours()).padStart(2, '0');
                const minutes = String(d.getMinutes()).padStart(2, '0');
                const seconds = String(d.getSeconds()).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                const timestamp = new Date(formattedDate).getTime();
                return Math.floor(timestamp / 1000); // 转换为秒级时间戳
            };

            // 先设置当前页为1
            this.currentPage = 1;

            // 构建搜索参数，确保分页参数正确
            this.searchParams = {
                ...this.form,
                start_time: formatDate(this.form.start_time),
                end_time: formatDate(this.form.end_time),
            };

            // Remove empty string properties from searchParams before sending
            Object.keys(this.searchParams).forEach(key => {
                if (this.searchParams[key] === '' || this.searchParams[key] === null) { // Check for null as well
                    delete this.searchParams[key];
                }
            });

            this.fetchAdminList(this.searchParams);
        },
        reset() {
            this.form = {
                search: "",
                source: "",
                is_up: "",
                state: "",
                start_time: "",
                end_time: ""
            };
            this.searchParams = {}; // Clear stored search params
            this.currentPage = 1;
            this.pageSize = 15;

            // 使用明确的分页参数进行请求
            this.fetchAdminList({
                page: 1,
                limit: 15,
                per_page: 15,
                pageSize: 15
            });
        },
        toShowDialog(e) {
            this.$router.push({path: "userManage/zhi", query: {id: e.id, type: 1}})
        },
        toShowDialog1(e) {
            this.$router.push({path: "userManage/gua", query: {id: e.id, type: 2}})
        },
        // exportToExcel() {
        //     // 准备要导出的数据
        //     const exportData = [
        //         ['服务商等级', '服务商', '业绩'],
        //         ['服务商1', this.userServerList.serverOne, this.userServerList.moneyOne],
        //         ['服务商2', this.userServerList.serverTwo, this.userServerList.moneyTwo],
        //         ['服务商3', this.userServerList.serverThree, this.userServerList.moneyThree]
        //     ];
        //
        //     // 创建工作簿和工作表
        //     const wb = XLSX.utils.book_new();
        //     const ws = XLSX.utils.aoa_to_sheet(exportData);
        //     XLSX.utils.book_append_sheet(wb, ws, '服务商列表');
        //
        //     // 导出Excel文件
        //     XLSX.writeFile(wb, '服务商列表.xlsx');
        // }
    }
};
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.dialog-content {
    padding: 10px;
}

.info-row {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 10px;
}

.label {
    width: 80px;
    text-align: right;
    line-height: 36px;
    color: #666;
}

.service-provider,
.performance {
    line-height: 36px;
    background-color: #f4f4f4;
    padding: 0 10px;
    border-radius: 4px;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.dialog-content {
    padding: 10px;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

/deep/ .el-dialog__header {
    padding: 10px !important;
    text-align: center;
}

.admin-page {
    padding: 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);

    .page-header {
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #f0f2f5;

        .header-title {
            font-size: 20px;
            font-weight: 600;
            color: #1f2937;
            line-height: 1.4;
        }
    }

    .table-header {
        margin-bottom: 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .table-title {
            font-size: 16px;
            font-weight: 500;
            color: #374151;
        }

        .table-actions {
            .el-button {
                margin-left: 12px;
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-1px);
                }
            }
        }
    }

    .el-tabs {
        margin-top: 16px;

        :deep(.el-tabs__header) {
            margin-bottom: 28px;
            border-bottom: 2px solid #f0f2f5;
        }

        :deep(.el-tabs__item) {
            font-size: 15px;
            padding: 0 28px;
            height: 44px;
            line-height: 44px;
            transition: all 0.3s;

            &.is-active {
                color: #2563eb;
                font-weight: 500;
            }

            &:hover {
                color: #2563eb;
            }
        }

        :deep(.el-tabs__active-bar) {
            height: 2px;
            background-color: #2563eb;
            transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
        }
    }

    .el-table {
        margin-top: 12px;
        border-radius: 8px;
        overflow: hidden;

        :deep(th) {
            background-color: #f9fafb !important;
            font-weight: 500;
            color: #4b5563;
        }

        :deep(td) {
            padding: 12px 0;
        }

        .delete-btn {
            color: #dc2626;
            transition: all 0.3s;

            &:hover {
                color: #ef4444;
            }
        }
    }

    .el-pagination {
        margin-top: 24px;
        padding: 12px 0;
        text-align: right;

        :deep(.el-pagination__total) {
            margin-right: 12px;
        }

        :deep(.btn-prev),
        :deep(.btn-next) {
            border-radius: 4px;
            background-color: #fff;
        }

        :deep(.el-pager li) {
            border-radius: 4px;
            background-color: #fff;

            &.active {
                background-color: #2563eb;
            }
        }
    }

    .el-dialog {
        border-radius: 12px;
        overflow: hidden;
        max-height: 90vh;
        display: flex;
        flex-direction: column;

        :deep(.el-dialog__header) {
            padding: 20px 24px !important;
            border-bottom: 1px solid #f0f2f5;
            margin: 0;

            .el-dialog__title {
                font-size: 18px;
                font-weight: 600;
                color: #1f2937;
            }
        }

        :deep(.el-dialog__body) {
            padding: 32px 24px;
            flex: 1;
            overflow-y: auto;

            .el-form-item {
                .el-input,
                .el-select {
                    width: 320px;
                }
            }
        }

        :deep(.el-tree) {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #DCDFE6;
            border-radius: 4px;
            padding: 10px;
        }

        :deep(.el-dialog__footer) {
            padding: 16px 24px;
            border-top: 1px solid #f0f2f5;
        }

        :deep(.el-form-item__label) {
            font-weight: 500;
            color: #374151;
        }

        :deep(.el-button) {
            padding: 8px 20px;
            transition: all 0.3s;

            &:hover {
                transform: translateY(-1px);
            }
        }
    }
}

.tip-text {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    display: block;
}

/deep/ .el-tab-pane {
    height: 650px;
    overflow-y: auto;
}

/* Added styles for search items and labels */
.search-item {
    margin-right: 10px; /* Add some right margin */
}
.search-label {
    margin-right: 5px; /* Space between label and input */
    white-space: nowrap; /* Prevent label text wrapping */
    font-size: 14px; /* Consistent font size */
    color: #606266; /* Standard label color */
    min-width: 60px; /* Minimum width for alignment */
    text-align: right; /* Align label text to the right */
}

</style>
